using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO.Ports;
using System.IO;

namespace FEZ_Cobra_Console_Application1
{
    public class VideoFeed
    {
   //     byte[] image;
        //bool useCamera = false;
        bool connected = false;
        bool sendVideo = true;
        public Socket server;
        public IPEndPoint remoteEndPoint;
        Thread videoThread;
        SdCard mySD = new SdCard();
        //SerialPort mySerial = new SerialPort("COM3", 115200);
        LinkspriteCamera Camera1 = new LinkspriteCamera(new SerialPort("COM3", 38400, Parity.None, 8, StopBits.One));
 //       DateTime startTime = DateTime.Now;

        public VideoFeed()
        {
            mySD.MountSDCard();
            
                //Camera.SetPictureSize(LinkspriteCamera.SET_SIZE_160x120);
                //Camera.Reset();
                //Debug.Print("Size change succesful");
                //initialize camera

            //set up network stream
            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            remoteEndPoint = new IPEndPoint(Wifi.serverIPAddress, 442);
      //      image = new byte[3] { 3, 4, 5 }; //dummy data

            connected = true;
        }

        public void writeToSD()
        {

            if (File.Exists(@"\SD\test.jpeg"))
            {
                File.Delete(@"\SD\test.jpeg");
            }

            //Camera.SetPictureSize(LinkspriteCamera.SET_SIZE_160x120);
            //        //Debug.Print("Size change failed!");
            //Debug.Print("Size Changed");
            //Camera.Reset();

            //SerialPort mySerial = new SerialPort("COM3", 115200);
            //mySerial.Close();

            
            //if(!(Camera.SetBR_115200()))
            //    Debug.Print("Failed");
 
            //    Debug.Print("BR change failed") ;
            //Debug.Print("BR Changed");

            //Camera1.Stop();
            //LinkspriteCamera Camera2 = new LinkspriteCamera(new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One));
            Camera1.SetBR_115200();
          
            
            DateTime startTime = DateTime.Now;
            if(Camera1.Reset())
            Camera1.GetPicture(mySD.WriteJPEGtoSD);
            DateTime endTime = DateTime.Now;
            TimeSpan timeTaken = endTime - startTime;
            Debug.Print("Time : " + timeTaken.ToString());
            mySD.unMountSD();
        }


        /// <summary>
        /// Send byte array to control server via UDP
        /// </summary>
        /// <param name="sendB"></param>
        public void send_UDP(byte[] sendB)
        {
            Wifi.sendingData = false;   //pause all other communication operations to send picture
            Thread.Sleep(200);          //Give us .2 a second to finish up any other operations
            //if (Wifi.sendingData)
            //    return;
            //sendB = new byte[] { 0, 5, 10, 15, 20 };
            if (connected && (server != null)/* && (sendB.Length > 3)*/)
            {
                server.SendTo(sendB, remoteEndPoint);
            }
            Wifi.sendingData = true;
        }

        public void startVideo()
        {
            sendVideo = true;
            videoThread = new Thread(new ThreadStart(sendFrames));
            videoThread.Start();
        }

        public void stopVideo()
        {
            sendVideo = false;
            try
            {
                videoThread.Abort();
            }
            catch(Exception a)
            {
                //no surprise here
            }
        }

        public void sendFrames()
        {
            while (sendVideo)
            {
                if (Camera1.Reset())
                    Camera1.GetPicture(Wifi.send_UDP);

//////                DateTime endTime = DateTime.Now;
////////                send_UDP(image);
//////                TimeSpan timeTaken = endTime - startTime;
//////                Debug.Print("Time : " + timeTaken.ToString());
//////                //Thread.Sleep(20000); //pre emtive frame rate
                Debug.Print("=+ Sent Image +=");
            }
        }

        public void loadImage()
        {

            //PUT IMAGE IN BYTE ARRAY HERE. FOR NOW WE WILL GET FROM SD CARD
            //FOR NOW WE GET IT FROM SDCARD
            //image = SdCard.ReadfromSD();
        }
        public static readonly byte[] SET_SIZE_160x120 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x22 };
        public static readonly byte[] SET_SIZE_320x240 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x11 };
        public static readonly byte[] SET_SIZE_640x480 = new byte[] { 0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, 0x00 };

    }
}
